<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require 'global_default_function.php';

function getOperationRecord($user, $optLevel) {
	$recordType = 1;
	if($user['userType'] == 2){
		$recordType = 2;
	}
	$result = HttpPost('https://api.baidu.com/json/sms/service/ToolkitService/getOperationRecord', json_encode([
		'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
		'body'=>[
			'startDate' => date("Y-m-d", strtotime("-10 day")),
			'endDate' => date("Y-m-d"),
			'optTypes'=> null,
			"recordType"=> $recordType,
			"optLevel"=> $optLevel
		]
	]));
	if(empty($result)) {
		return false;
	}
	$jsondata = json_decode ($result);
	if( isset( $jsondata->body->data[0] ) ) {
		return $jsondata->body->data;
	}
	return false;
}

run(function() use ($argv) {
	showMessage('查询历史操作记录.' );
	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}
  $userList = $database->query('SELECT `id`, `companyId`, `userid`, `customerid`, `contact`, `username`, `password`, `token`, `userType`, `bazaarId` FROM cfg_expand where `status` = 1 and `userType` BETWEEN 1 and 2');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}
	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			for ($i=1; $i<=5; $i++) {
				switch ($i) {
					case 1:
						showMessage($user['username'].'推广单元历史操作记录.' );
						break;  
					case 2:
						showMessage($user['username'].'推广计划历史操作记录.' );
						break;
					case 3:
						showMessage($user['username'].'帐户历史操作记录.' );
						break;
					case 4:
						showMessage($user['username'].'创意历史操作记录.' );
						break;
					case 5:
						showMessage($user['username'].'关键词历史操作记录.' );
						break;
				}
				go(function() use ($config, $user, $i)  {
					$jsondata = getOperationRecord($user, $i);
					if(is_array($jsondata)) {
						$database = new MySQL;
						$connect = $database->connect($config);
						if( $connect) {
							foreach ($jsondata as $value ) {
								$oldValue = (string)$value->oldValue;
								$newValue = (string)$value->newValue;
								$value->unitId = isset($value->unitId) ? $value->unitId : 0;
								$value->planId = isset($value->planId) ? $value->planId : 0;
								$value->optContent = isset($value->optContent) ? $value->optContent : 0;
								$value->optTime = isset($value->optTime) ? strtotime($value->optTime) : time();
								if($value->optContent) {
									$md5 = md5($user['companyId'].$user['userType'].json_encode($value, JSON_FORCE_OBJECT));
									$res = $database->query("select id from cfg_optlog where md5 = '{$md5}' LIMIT 1");
									if( !isset($res[0]['id']) ) {
										$database->query("INSERT INTO cfg_optlog (`companyId`, `userType`, `userId`, `bazaarId`, `customerid`, `contact`, `planId`, `unitId`, `optTime`, `optContent`, `optType`, `optLevel`, `oldValue`, `newValue`, `optObj`, `md5` )
											values ( '{$user['companyId']}', '{$user['userType']}', '{$value->userId}', '{$user['bazaarId']}', '{$user['customerid']}', '{$user['contact']}', '{$value->planId}', '{$value->unitId}','{$value->optTime}', '{$value->optContent}', '{$value->optType}',
												'{$value->optLevel}', '{$oldValue}', '{$newValue}', '{$value->optObj}', '{$md5}' )" );
									} else {
										$database->query( " UPDATE cfg_optlog SET `bazaarId` = '{$user['bazaarId']}' WHERE id = '{$res[0]['id']}'; ");
									}
								}
							}
						}
					}
				});
			}
		}
		Swoole\Coroutine::sleep(2);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');